/*
 * @Author: zi.yang
 * @Date: 2022-02-05 23:29:08
 * @LastEditors: zi.yang
 * @LastEditTime: 2022-02-08 16:32:45
 * @Description: In User Settings Edit
 * @FilePath: \api-generator\app\utils\ajaxResponse.js
 */
'use strict';
const { isString, isBoolean } = require('../utils/types');

class AjaxResponse {
  // 响应数据返回格式
  static base(res) {
    const success = isBoolean(res.success) ? res.success : true;
    const data = res.data || null;
    const code = res.code || 200;
    const msg = res.msg || '';
    if (success) {
      return { success, code, msg, data };
    }
    const error = res.error || '未捕获异常信息';
    const errorConfig = {
      msg: error.toString(),
      conf: JSON.parse(JSON.stringify(error)),
    };
    return { success, code, msg, data, errorConfig };

  }

  // 请求成功
  static success(res) {
    const data = res.data || null;
    const code = res.code || 200;
    const msg = res.msg || '操作成功';
    if (isString(res)) {
      return this.base({ success: true, code, data, msg: res });
    }
    return this.base({ success: true, code, data, msg });
  }

  // 请求失败
  static error(res) {
    const data = res.data || null;
    const code = res.code || 500;
    const msg = res.msg || '操作失败';
    if (isString(res)) {
      return this.base({ success: false, code, data, msg: res });
    }
    const error = res.error;
    return this.base({ success: false, code, data, msg, error });
  }

  // 身份失效
  static identityFailure(res) {
    const data = res.data || null;
    const code = res.code || 403;
    const msg = res.msg || '身份认证已超时，请重新登陆！';
    if (isString(res)) {
      return this.base({ msg: res });
    }
    return this.base({ success: false, code, data, msg });
  }
}

module.exports = AjaxResponse;
